# Filters added to this controller will be run for all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
require 'login_system'
require 'htmlentities'

class ApplicationController < ActionController::Base
  include LoginSystem
  layout 'default'
  theme :get_theme
  before_filter :initvars
  before_filter :config_mailer
  
  def initvars
    session[:currentpage]=request.request_uri
    if session[:currentpage]=="/media/rss"
      session[:currentpage]="/"
    end
    if session[:loadedsettings]==nil
      @settings=Setting.find(:first)
      session[:loadedsettings]=@settings
    else
      @settings=session[:loadedsettings]
    end
    if cookies["theme"]!=nil
      session[:loadedsettings]["theme"]=cookies["theme"]
    end
    if cookies["language"]!=nil
      Localization.lang=cookies["language"]
      session[:language]=cookies["language"]
    else
      Localization.lang='en_US'
      session[:language]='en_US'
    end
  end
    
  def rescue_action_in_public(exception)
    redirect_to :controller => "media", :action => "error" , :msg => exception
  end
    
  def local_request?
    false
  end

  def get_theme
     @settings=session[:loadedsettings]
     return @settings.theme.nil? ? "default": @settings.theme
  end
  
  def init_extplugin
    @plugins= Dir.entries(RAILS_ROOT+"/components/plugin/")
		
    for plug in @plugins
      if plug.gsub!(/_controller.rb/,"")
        if Extplugin.find_by_name(plug.to_s)==nil
          @ext=Extplugin.new
          @ext.name=plug.to_s
          @ext.activated=0
		      @ext.config=Hash["title"=>plug.to_s]
          @ext.save
        end
      end
    end	
  end

  def matchplugin
    @exts=Extplugin.find(:all)
	  for registered in @exts
	    if !File.exists?(RAILS_ROOT+"/components/plugin/"+registered.name.to_s+"_controller.rb") 
	      registered.destroy
	    end 
	  end
  end
	 
  def config_mailer
    @settings=Setting.find(:first)
    ActionMailer::Base.smtp_settings = {
      :address => @settings.mail_host,
      :port => @settings.mail_port,
      :domain => @settings.mail_domain,
	  }
	  if @settings.mail_authentication!="none"
      ActionMailer::Base.smtp_settings["authentication"] = @settings.mail_authentication
      ActionMailer::Base.smtp_settings["user_name"] = @settings.mail_user
      ActionMailer::Base.smtp_settings["password"] = @settings.mail_password
	  else
	    ActionMailer::Base.smtp_settings["authentication"] = nil
      ActionMailer::Base.smtp_settings["user_name"] = nil
      ActionMailer::Base.smtp_settings["password"] = nil
	  end
  end

end